package org.example.tools;

import java.sql.*;

public class jdbcUtils {

    // 获取数据库连接
    public static Connection getConnection() throws ClassNotFoundException, SQLException, SQLException {
        // 注册JDBC驱动
        Class.forName("com.mysql.jdbc.Driver");
        //  2.创建对象连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo02",
                "jdbc2","jdbc123");
        return conn;
    }

    // 执行查询语句
    public static ResultSet executeQuery(String sql, Connection connection) throws SQLException {
        Statement statement = connection.createStatement();
        return statement.executeQuery(sql);
    }

    // 执行更新操作
    public static int executeUpdate(String sql, Connection connection) throws SQLException {
        Statement statement = connection.createStatement();
        return statement.executeUpdate(sql);
    }
    // 执行新增操作
    public static int executeInsert(String sql, Connection connection) throws SQLException {
        Statement statement = connection.createStatement();
        return statement.executeUpdate(sql);
    }
    //关闭数据库连接
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
